package com.ljy.my_study.lintcode.LFU缓存;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author James
 * @date 2018年9月25日
 */
public class LFUCache2 {
	private int capacity;

	private Map<Integer,Entry> map=new LinkedHashMap<>();
	private PriorityQueue<Entry> queue;
	
	/*
	 * @param capacity: An integer
	 */
	public LFUCache2(int capacity) {
		this.capacity=capacity;
		this.map=new LinkedHashMap<>();
		
		this.queue=new PriorityQueue<>(capacity,new Comparator<Entry>() {
			@Override
			public int compare(Entry o1, Entry o2) {
				if(o1.getWeight()>o2.getWeight()) {
					return -1;
				}else {
					return 1;
				}
			}
		});
	}

	/*
	 * @param key: An integer
	 * 
	 * @param value: An integer
	 * 
	 * @return: nothing
	 */
	public void set(int key, int value) {
		if(queue.size()>=capacity) {
			Entry e=(Entry) (queue.toArray())[queue.size()-1];
			if(e!=null) {
				map.remove(e.getKey());
			}
			(queue.toArray())[queue.size()-1]=null;
		}
		Entry e=new Entry(key,value);
		queue.add(e);
		map.put(key, e);
	}

	/*
	 * @param key: An integer
	 * 
	 * @return: An integer
	 */
	public int get(int key) {
		Entry e=map.get(key);
		if(e!=null) {
			int w=e.getWeight();
			e.setWeight(++w);
			System.out.println(e.getValue());
			return e.getValue();
		}
		System.out.println(-1);
		return -1;
	}
	
	public static class Entry {
		private int weight;
		
		private int key;
		private int value;
		public Entry(int key, int value) {
			super();
			this.weight=1;
			this.key = key;
			this.value = value;
		}
		public int getKey() {
			return key;
		}
		public void setKey(int key) {
			this.key = key;
		}
		public int getValue() {
			return value;
		}
		public void setValue(int value) {
			this.value = value;
		}
		public int getWeight() {
			return weight;
		}
		public void setWeight(int weight) {
			this.weight = weight;
		}
	}
}
